package com.youlai.dynamicdatasource.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.youlai.dynamicdatasource.model.User;
import com.youlai.dynamicdatasource.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/api/users")
@Slf4j
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {

        log.info("读取用户{}", id);
        try {
            DynamicDataSourceContextHolder.push("slave");
            User user = userService.getById(id);
            int i = 1 / 0;
            return user;
        } finally {
            DynamicDataSourceContextHolder.poll();
        }


    }

    @PostMapping
    public boolean createUser(@RequestBody User user) {
        log.info("新增用户：{}", JSONUtil.toJsonStr(user));
        boolean result = userService.save(user);
        log.info("新增用户结果：{}", result);
        return result;
    }
}
